package org.wyw.solution;

import org.wyw.entiry.ListNode;

@Solution(
        id = 7,
        title = "环形链表",
        difficulty = "medium",
        link = "https://leetcode.cn/problems/linked-list-cycle/description/"
)
public class Solution007 {
    /**
     * 思路：快慢指针，慢指针每次走一步，快指针每次走两步，如果快指针追上慢指针，则说明有环
     * @param head
     * @return
     */
    public boolean hasCycle(ListNode head) {
        if (head == null || head.next == null) {
            return false;
        }
        ListNode slow = head;
        ListNode fast = head;
        //若 没有环，则while会根据 fast != null && fast.next != null 跳出循环，有环，则会从return 跳出循环
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
            if (fast == slow) {
                return true;
            }
        }
        return false;
    }
}
